<?php
require_once '../config/database.php';
require_once '../utils/Database.php';
require_once '../utils/Response.php';

$db = new Database();

// 设置响应头
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';
$input = json_decode(file_get_contents('php://input'), true);

// 获取IP地址
function getClientIp() {
    $ipKeys = ['HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR'];
    foreach ($ipKeys as $key) {
        if (array_key_exists($key, $_SERVER) && !empty($_SERVER[$key])) {
            $ip = explode(',', $_SERVER[$key])[0];
            if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
                return $ip;
            }
        }
    }
    return $_SERVER['REMOTE_ADDR'] ?? 'unknown';
}

// 获取用户代理
function getUserAgent() {
    return $_SERVER['HTTP_USER_AGENT'] ?? '';
}

// 记录登录日志
function logLogin($adminId, $username, $status, $reason = null) {
    global $db;
    
    $db->insert('admin_login_logs', [
        'admin_id' => $adminId,
        'username' => $username,
        'ip_address' => getClientIp(),
        'user_agent' => getUserAgent(),
        'login_status' => $status,
        'failure_reason' => $reason
    ]);
}

// 记录操作日志
function logOperation($adminId, $username, $action, $module, $description, $requestData = null) {
    global $db;
    
    $db->insert('admin_operation_logs', [
        'admin_id' => $adminId,
        'username' => $username,
        'action' => $action,
        'module' => $module,
        'description' => $description,
        'request_data' => $requestData ? json_encode($requestData) : null,
        'ip_address' => getClientIp(),
        'user_agent' => getUserAgent()
    ]);
}

// 生成JWT Token（简化版）
function generateToken($adminData) {
    $header = json_encode(['typ' => 'JWT', 'alg' => 'HS256']);
    $payload = json_encode([
        'admin_id' => $adminData['id'],
        'username' => $adminData['username'],
        'role_id' => $adminData['role_id'],
        'exp' => time() + (24 * 60 * 60) // 24小时过期
    ]);
    
    $headerEncoded = base64url_encode($header);
    $payloadEncoded = base64url_encode($payload);
    
    $signature = hash_hmac('sha256', $headerEncoded . "." . $payloadEncoded, 'your-secret-key', true);
    $signatureEncoded = base64url_encode($signature);
    
    return $headerEncoded . "." . $payloadEncoded . "." . $signatureEncoded;
}

// Base64 URL编码
function base64url_encode($data) {
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

// Base64 URL解码
function base64url_decode($data) {
    return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT));
}

// 验证Token
function verifyToken($token) {
    if (!$token) return false;
    
    $parts = explode('.', $token);
    if (count($parts) !== 3) return false;
    
    list($headerEncoded, $payloadEncoded, $signatureEncoded) = $parts;
    
    $signature = base64url_encode(hash_hmac('sha256', $headerEncoded . "." . $payloadEncoded, 'your-secret-key', true));
    
    if ($signature !== $signatureEncoded) return false;
    
    $payload = json_decode(base64url_decode($payloadEncoded), true);
    
    if ($payload['exp'] < time()) return false;
    
    return $payload;
}

// 获取当前管理员
function getCurrentAdmin() {
    $authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
    
    if (strpos($authHeader, 'Bearer ') === 0) {
        $token = substr($authHeader, 7);
        $payload = verifyToken($token);
        
        if ($payload) {
            global $db;
            $admin = $db->fetchOne("
                SELECT a.*, r.name as role_name, r.display_name as role_display_name, r.permissions
                FROM admin_users a
                LEFT JOIN admin_roles r ON a.role_id = r.id
                WHERE a.id = ? AND a.status = 'active'
            ", [$payload['admin_id']]);
            
            if ($admin) {
                $admin['permissions'] = json_decode($admin['permissions'] ?? '[]', true);
                return $admin;
            }
        }
    }
    
    return null;
}

// 检查权限
function hasPermission($permission) {
    $admin = getCurrentAdmin();
    if (!$admin) return false;
    
    return in_array($permission, $admin['permissions']);
}

switch ($method) {
    case 'POST':
        switch ($action) {
            case 'login':
                // 管理员登录
                if (!isset($input['username']) || !isset($input['password'])) {
                    Response::error('用户名和密码不能为空');
                }
                
                $username = trim($input['username']);
                $password = $input['password'];
                
                if (empty($username) || empty($password)) {
                    Response::error('用户名和密码不能为空');
                }
                
                // 查找管理员
                $admin = $db->fetchOne("
                    SELECT a.*, r.name as role_name, r.display_name as role_display_name, r.permissions
                    FROM admin_users a
                    LEFT JOIN admin_roles r ON a.role_id = r.id
                    WHERE a.username = ?
                ", [$username]);
                
                if (!$admin) {
                    logLogin(null, $username, 'failed', '用户不存在');
                    Response::error('用户名或密码错误');
                }
                
                // 检查用户状态
                if ($admin['status'] !== 'active') {
                    logLogin($admin['id'], $username, 'failed', '账户已被禁用');
                    Response::error('账户已被禁用，请联系管理员');
                }
                
                // 验证密码
                if (!password_verify($password, $admin['password'])) {
                    logLogin($admin['id'], $username, 'failed', '密码错误');
                    Response::error('用户名或密码错误');
                }
                
                // 更新登录信息
                $db->update('admin_users', [
                    'last_login_time' => date('Y-m-d H:i:s'),
                    'last_login_ip' => getClientIp(),
                    'login_count' => $admin['login_count'] + 1,
                    'updated_at' => date('Y-m-d H:i:s')
                ], 'id = :id', ['id' => $admin['id']]);
                
                // 记录成功登录日志
                logLogin($admin['id'], $username, 'success');
                
                // 生成token
                $token = generateToken($admin);
                
                // 返回登录信息
                $adminInfo = [
                    'id' => $admin['id'],
                    'username' => $admin['username'],
                    'real_name' => $admin['real_name'],
                    'email' => $admin['email'],
                    'avatar' => $admin['avatar'],
                    'role_id' => $admin['role_id'],
                    'role_name' => $admin['role_name'],
                    'role_display_name' => $admin['role_display_name'],
                    'permissions' => json_decode($admin['permissions'] ?? '[]', true),
                    'last_login_time' => $admin['last_login_time']
                ];
                
                Response::success([
                    'token' => $token,
                    'admin' => $adminInfo
                ], '登录成功');
                break;
                
            case 'logout':
                // 退出登录
                $admin = getCurrentAdmin();
                if ($admin) {
                    logOperation($admin['id'], $admin['username'], 'logout', 'auth', '管理员退出登录');
                }
                
                Response::success([], '退出成功');
                break;
                
            case 'change_password':
                // 修改密码
                $admin = getCurrentAdmin();
                if (!$admin) {
                    Response::authError('请先登录');
                }
                
                if (!isset($input['old_password']) || !isset($input['new_password'])) {
                    Response::error('请提供原密码和新密码');
                }
                
                $oldPassword = $input['old_password'];
                $newPassword = $input['new_password'];
                
                if (strlen($newPassword) < 6) {
                    Response::error('新密码长度不能少于6位');
                }
                
                // 验证原密码
                $currentAdmin = $db->fetchOne("SELECT password FROM admin_users WHERE id = ?", [$admin['id']]);
                if (!password_verify($oldPassword, $currentAdmin['password'])) {
                    Response::error('原密码错误');
                }
                
                // 更新密码
                $newPasswordHash = password_hash($newPassword, PASSWORD_DEFAULT);
                $result = $db->update('admin_users', [
                    'password' => $newPasswordHash,
                    'updated_at' => date('Y-m-d H:i:s')
                ], 'id = :id', ['id' => $admin['id']]);
                
                if ($result) {
                    logOperation($admin['id'], $admin['username'], 'change_password', 'auth', '修改登录密码');
                    Response::success([], '密码修改成功');
                } else {
                    Response::error('密码修改失败');
                }
                break;
                
            default:
                Response::error('无效的操作');
        }
        break;
        
    case 'GET':
        switch ($action) {
            case 'profile':
                // 获取当前管理员信息
                $admin = getCurrentAdmin();
                if (!$admin) {
                    Response::authError('请先登录');
                }
                
                $adminInfo = [
                    'id' => $admin['id'],
                    'username' => $admin['username'],
                    'real_name' => $admin['real_name'],
                    'email' => $admin['email'],
                    'phone' => $admin['phone'],
                    'avatar' => $admin['avatar'],
                    'role_id' => $admin['role_id'],
                    'role_name' => $admin['role_name'],
                    'role_display_name' => $admin['role_display_name'],
                    'permissions' => $admin['permissions'],
                    'last_login_time' => $admin['last_login_time'],
                    'login_count' => $admin['login_count']
                ];
                
                Response::success($adminInfo, '获取成功');
                break;
                
            case 'check_permission':
                // 检查权限
                $permission = $_GET['permission'] ?? '';
                if (empty($permission)) {
                    Response::error('缺少权限参数');
                }
                
                $hasPermission = hasPermission($permission);
                Response::success(['has_permission' => $hasPermission], '检查完成');
                break;
                
            default:
                Response::error('无效的操作');
        }
        break;
        
    default:
        Response::error('不支持的请求方法');
}
?>